/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package io.renren.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import dm.jdbc.util.StringUtil;
import io.renren.annotation.Login;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.Result;
import io.renren.common.validator.ValidatorUtils;
import io.renren.dto.*;
import io.renren.dto.queryDto.BillCodeQuery;
import io.renren.entity.TradermEntity;
import io.renren.entity.UnionidmEntity;
import io.renren.entity.WxuserEntity;
import io.renren.factory.FeginClientFactory;
import io.renren.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.*;

/**
 * 登录接口
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/api/Login")
@Api(tags = "登录接口")
@AllArgsConstructor
public class ApiLoginController {
    private final TokenService tokenService;
    private final TradermService tradermService;
    private final WxuserService wxuserService;
    private final AutoService autoService;
    private final WechatNewService wechatNewService;

    @Autowired
    private UnionidmService unionidmService;

    @PostMapping("login")
    @ApiOperation("登录")
    public Result<Map<String, Object>> login(@RequestBody LoginDTO dto) {
        //表单校验
        ValidatorUtils.validateEntity(dto);
        // 校验手机号码
        if (StringUtil.isNotEmpty(dto.getMobile())) {
            String regex = "^1[3-9]\\d{9}$";
            boolean isMobile = dto.getMobile().matches(regex);
            if (!isMobile) {
                return new Result().error("手机号码格式错误");
            }
        }
        List<TradermEntity> userInfos = tradermService.findListByTel(dto.getMobile());
        TradermEntity userInfo = null;
        if (userInfos.size() > 1) {
            return new Result().error("手机号给多个客户使用，请联系客服");
        }
        if (userInfos.size() == 1) {
            userInfo = userInfos.get(0);
        }

        WxuserEntity wxUserInfo = wxuserService.findOneByOpenId(dto.getOpenId());

        // 根据 公众号的openid 查询
        // 1 插入 记录表
        UnionidmEntity unionidmEntity = unionidmService.findOneByOpenId(dto.getOpenId(), "2");

        String wxUserFk = "";
        String tradermFk = "";
        if (wxUserInfo != null) {
            wxUserFk = wxUserInfo.getWxuseroid();
        }
        try {
            if (userInfo != null) {
                tradermFk = userInfo.getTradermoid();
                userInfo.setMiniopenid(dto.getOpenId());
                tradermService.update(userInfo, new QueryWrapper<TradermEntity>().eq("TraderMOID", userInfo.getTradermoid()));
            }
            if (wxUserInfo != null && StringUtil.isNotEmpty(wxUserInfo.getTradermFk())) {
                TradermEntity temp = tradermService.findOneByTraderMOID(wxUserInfo.getTradermFk());
                if (temp == null) {
                    wxuserService.updateTradermFk(wxUserInfo);
                }
                wxUserFk = wxUserInfo.getWxuseroid();
            }
            if (userInfo == null) {
                tradermFk = UUID.randomUUID().toString();
                userInfo = new TradermEntity();
                userInfo.setTradermoid(tradermFk);

                BillCodeQuery query = new BillCodeQuery();
                query.setEncodeKind("客户");
                ReturnApiDto result = FeginClientFactory.getFeginClient(FeginClientProxy.class, "http://58.216.180.2:8405/").getBillCode(query);
                if (result != null) {
                    userInfo.setCode(result.getData() + "");
                }
                userInfo.setName(dto.getNickName() != null ? dto.getNickName() : "车友_" + new Date().getTime());
                userInfo.setTel(dto.getMobile());
                userInfo.setTradertype("客户");
                userInfo.setMiniopenid(dto.getOpenId());
                userInfo.setSourceway("小程序");
                userInfo.setSysCreated(new Date());
                userInfo.setSettlementtraderFk(tradermFk);
                userInfo.setBilltype("BTT");
                tradermService.insert(userInfo);
            }
            if (wxUserInfo == null) {
                wxUserFk = UUID.randomUUID().toString();
                wxUserInfo = new WxuserEntity();
                wxUserInfo.setBilltype("BWU");
                wxUserInfo.setWxuseroid(wxUserFk);
                wxUserInfo.setMiniopenid(dto.getOpenId());
                wxUserInfo.setTradermFk(tradermFk);
                wxUserInfo.setWxremark(dto.getMobile());
                wxUserInfo.setWxstartdate(new Date());
                wxUserInfo.setRegisterdate(new Date());
                wxUserInfo.setWxheadimageurl(dto.getHeadImg());
                wxUserInfo.setWxnickname(dto.getNickName());
                wxUserInfo.setWxremark(dto.getMobile());
                wxUserInfo.setWxsex(dto.getSex());
                wxUserInfo.setWxarea(dto.getArea());
                if (unionidmEntity != null) {
                    wxUserInfo.setUnionid(unionidmEntity.getUnionId());
                }
                wxuserService.insert(wxUserInfo);
            }
            // 绑定TraderM_FK
            if (wxUserInfo.getMiniopenid() == null) {
                wxuserService.updateFkAndRemarkByWxUserId(tradermFk, dto.getMobile(), wxUserFk);
            }
            // traderM 存在手机号 存在MiniOpenID openid不一致 提示已绑定
            if (StringUtil.isNotEmpty(userInfo.getMiniopenid()) && !userInfo.getMiniopenid().equals(dto.getOpenId())) {
                return new Result().error("手机号" + dto.getMobile() + ",已绑定");
            }
            userInfo = tradermService.findOneByTraderMOID(tradermFk);
            // 查询是否首次登录
            Boolean isEx = autoService.isExByFk(tradermFk);
            userInfo.setIsFirstLogin(1);
            if (isEx) {
                userInfo.setIsFirstLogin(0);
            }
            return new Result().ok(userInfo);

        } catch (Exception e) {
            return new Result().error(e.getMessage());
        }
    }


    @PostMapping("getMobileByCode")
    @ApiOperation("code换手机号")
    public Result<Map<String, Object>> getMobileByCode(@RequestBody WxInfoDTO dto) {
        WeChatAccessPhoneNumberVo weChatAccessPhoneNumberVo = wechatNewService.miniPhoneCode(dto.getCode());
        Map<String, Object> result = new HashMap<>();
        result.put("phoneNumber", weChatAccessPhoneNumberVo.getPhoneInfo());
        return new Result().ok(result);
    }

    @RequestMapping("setWxOpenId/{miniprogramOpenId}")
    @ApiOperation("code换手机号")
    public Result setWxOpenId(@PathVariable String miniprogramOpenId, @RequestParam String code) {
        TradermEntity tradermEntity = tradermService.findByMiniOpenId(miniprogramOpenId);
        if (tradermEntity != null) {
            String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" + "appid=wxd433a91dbcfde638" + "&secret=f296f3be7953f98b94783a6fe46ffd65" + "&code=" + code + "&grant_type=authorization_code";
//            String result = HttpUtils.sendGet(url, ""); // 发起GET请求换取openid等数据
//            JSONObject responseJson = JSONObject.parseObject(result);
//            logger.info("微信公众号响应参数：{}", responseJson);
//            if (ObjectUtils.isEmpty(responseJson.getString("openid"))) {
//                throw new IllegalArgumentException(responseJson.toJSONString());
//            }
//            String openId = responseJson.getString("openid");

        }

        return new Result();
    }


    @PostMapping("getOpenIdByCode")
    @ApiOperation("code获取openId")
    public Result<Map<String, Object>> getOpenIdByCode(@RequestBody WxInfoDTO dto) {
        WeChatMiniAuthorizeVo weChatAccessPhoneNumberVo = wechatNewService.miniAuthCode(dto.getCode());
        // 判定是否有 unionid
        if (StringUtil.isNotEmpty(weChatAccessPhoneNumberVo.getUnionId())) {
            // 1 插入 记录表
            UnionidmEntity unionidmEntity = unionidmService.findOneByOpenId(weChatAccessPhoneNumberVo.getOpenId(), "2");
            if (unionidmEntity == null) {
                unionidmEntity = unionidmService.saveInfoMini(weChatAccessPhoneNumberVo);
            }

            // 2 先根据小程序的 openid 去找 用户信息表 ， 有的话 则更新 对于的 unionid
            WxuserEntity wxuserEntity = wxuserService.findOneByMiniOpenId(weChatAccessPhoneNumberVo.getOpenId());
            if (wxuserEntity != null) {
                wxuserEntity.setUnionid(unionidmEntity.getUnionId());
                wxuserService.updateUnionIdByMiniOpenId(wxuserEntity);
            }
            // 3 根据对于的 unionid  获取 记录表
            UnionidmEntity wxUnionidmEntity = unionidmService.findOneByUnionId(weChatAccessPhoneNumberVo.getUnionId(), "1");
            if (wxUnionidmEntity != null) {
                // 4 根据 unionid 去查询用户表
                wxuserEntity = wxuserService.findOneByUnionid(weChatAccessPhoneNumberVo.getUnionId());
                if (wxuserEntity != null) {
                    // 5 根据用户对于的 wxopneid 去更新
                    wxuserEntity.setWxopenid(wxUnionidmEntity.getOpenId());
                    wxuserService.updateWxOpenIdByUnionId(wxuserEntity);

                    tradermService.updateWxOpenIdByMiniOpenId(wxUnionidmEntity.getOpenId(), weChatAccessPhoneNumberVo.getOpenId());
                    return new Result().ok(weChatAccessPhoneNumberVo.getOpenId());
                }
            }

        }
        return new Result().ok(weChatAccessPhoneNumberVo.getOpenId());
    }

    @PostMapping("clearCacheFlag")
    @ApiOperation("code获取openId")
    public Result<Map<String, Object>> clearCacheFlag(@RequestBody ClearCacheFlagDTO dto) {
        Map<String, Object> result = new HashMap<>();
        result.put("clearCache", 0);
        if (StringUtil.isNotEmpty(dto.getMobile())) {
            TradermEntity userInfo = tradermService.findOneByTel(dto.getMobile());
            if (userInfo == null) {
                result.put("clearCache", 1);
                return new Result().ok(result);
            }
            if (userInfo != null && userInfo.getMiniopenid() == null) {
                result.put("clearCache", 1);
                return new Result().ok(result);
            }
        }
        if (StringUtil.isNotEmpty(dto.getOpenId())) {
            WxuserEntity wxuserEntity = wxuserService.findOneByOpenId(dto.getOpenId());
            if (wxuserEntity == null) {
                result.put("clearCache", 1);
                return new Result().ok(result);
            }
        }
        return new Result().ok(result);
    }

    @PostMapping("getTraderMFkFromMobile")
    @ApiOperation("根据手机号查询 traderM_FK")
    public Result<Map<String, Object>> getTraderMFkFromMobile(@RequestBody ClearCacheFlagDTO dto) {
        Map<String, Object> result = new HashMap<>();
        TradermEntity userInfo = tradermService.findOneByTel(dto.getMobile());
        if (userInfo != null) {
            result.put("TraderMOID", userInfo.getTradermoid());
            result.put("MiniOpenID", userInfo.getMiniopenid());
        }
        return new Result().ok(result);
    }


}